<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  <link rel="stylesheet" href="/static/style.css" />
  <title>文档合规检查</title>
</head>
<body>
  <div class="container">
    <h1>在线文档合规检查</h1>
    <form id="upload-form" action="/submit" method="post" enctype="multipart/form-data">
      <label>邮箱: <input type="email" name="email" required /></label>
      <label>文档名称: <input type="text" name="doc_name" id="doc_name" required /></label>
      <label>文档类型:
        <select name="doc_type">
            {% for item in prompt_list %}
            <option value="{{ item.key }}">{{ item.name }}</option>
            {% endfor %}
        </select>
      </label>
      <label>上传文档: 
        <input type="file" name="file" id="file_input" accept=".pdf,.docx,.pptx" required />
      </label>
      <button type="submit">提交</button>
    </form>
    <div id="message" style="margin-top: 1em; font-weight: bold;"></div>
  </div>

  <script>
    const form = document.getElementById('upload-form');
    const msg = document.getElementById('message');
    const fileInput = document.getElementById('file_input');
    const docNameInput = document.getElementById('doc_name');

    // 功能1：选择文件后自动填入文档名称（不带扩展名）
    fileInput.addEventListener('change', () => {
      const file = fileInput.files[0];
      if (file) {
        const nameWithoutExt = file.name.replace(/\.[^/.]+$/, "");
        docNameInput.value = nameWithoutExt;
      }
    });

    // 功能2：提交上传后显示提示，并在成功后重置部分字段
    form.addEventListener('submit', async (e) => {
      e.preventDefault();
      msg.textContent = '正在上传文件，请稍候...';
      msg.style.color = 'black';

      try {
        const data = new FormData(form);
        const res = await fetch('/submit', {
          method: 'POST',
          body: data
        });

        const json = await res.json();
        if (res.ok) {
          msg.textContent = json.message || '上传成功';
          msg.style.color = 'green';

          // ✅ 清除文档名和文件选择框
          docNameInput.value = '';
          fileInput.value = '';
        } else {
          msg.textContent = json.error || '上传失败';
          msg.style.color = 'red';
        }
      } catch (err) {
        msg.textContent = '网络错误或服务器无响应';
        msg.style.color = 'red';
      }
    });
  </script>
</body>
</html>
